package com.ym.component;

import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
@Component
public class Job {

    //分片广播
    @XxlJob("testJob")
    public void job(){
        // 分片参数
        int index = XxlJobHelper.getShardIndex();
        int total = XxlJobHelper.getShardTotal();
        log.info("分片参数：当前分片序号 = {}, 总分片数 = {}", index, total);
        //实际开发中应该是从数据库查询的list
        List<String> list = Stream.of("a", "b", "c", "d", "e")
                .collect(Collectors.toList());
        itemJob(list, index, total);
    }

    //每个分片执行
    private void itemJob(List<String> list, int index, int total) {
        //总数
        int totalCount = list.size();
        //初始下标
        int start = (totalCount / total) * index;
        //结束下标，最后一个分片处理剩余所有的任务
        //int end = Math.min(start + totalCount / total, totalCount);
        //if (index == total - 1) {
        //    end = totalCount;
        //}
        int end = (index == total - 1) ? totalCount : Math.min(start + totalCount / total, totalCount);

        for (int i = start; i < end; i++) {
            log.info(list.get(i));
        }
    }
}
